import React, { useEffect, useMemo, useState,useRef } from 'react'
import {View, Button,Image,Text} from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
import Taro, { useDidShow } from '@tarojs/taro'
import CountDownTimer from '@/components/countdown-timer'
import InputNumber from '@/components/InputNumber'
import wx from '@/utils/weixin-js-sdk/index';

import './index.less'
import "taro-ui/dist/style/components/action-sheet.scss";
import {debounce} from '@/utils/helper'

export default function OrderConfirm() {
  const { router } = Taro.getCurrentInstance()
  const [PopupService, setPopupService] = useState(false)
  const [info,setInfo] = useState({})
  const [time, settime] = useState(0)
  const couponRef = useRef({})
  const [curCoupon, setCurCoupon] = useState([])
  const [goodsList, setgoodsList] = useState([])
  const [goodsPrice, setgoodsPrice] = useState(0)
  const [goodsNum, setgoodsNum] = useState(0)
  const [priceMap, setPriceMap] = useState({
    totalPrice: 0,
    ticketPrice: 0
  })
  const [watchList, setwatchList] = useState([])
  const [curCheckbox, setcurCheckbox] = useState(null)

  useEffect(()=>{
    const fetchData = async e=>{
      Taro.showLoading({title:'加载中...'})
      const res = await Taro.$get(`/act/orders/${Taro.getCurrentInstance().router.params.orderId}`,'',1)
      if(res.code === '1'){
        setInfo(res.content)
        Taro.setNavigationBarTitle({
          title:res.content?.title || '确认订单'
        })
        setPriceMap({
          totalPrice: res.content.totalPayment*1,
          ticketPrice: res.content.totalPayment*1
        })
        const time = new Date(res.content.closedAt.replace(/-/g, '/')).getTime() - (res.content.systemTime?new Date(res.content.systemTime.replace(/-/g, '/')).getTime(): Date.now())
        Taro.$get(`/act/activities/storeGoods`,{
          activityId:res.content.activityId,
          pageSize:5
        }).then(ret=>{
          setgoodsList(ret.content.list || [])
        })
        if(time < 1){
          Taro.$toast('该订单已失效!')
          setTimeout(()=>{
            Taro.navigateBack()
          },1000)
          return;
        }
        settime(time)
      }
      Taro.eventCenter.off('changeCoupon')
      Taro.eventCenter.on('changeCoupon', async (data)=>{
        if(data.ticket){
          couponRef.current = {...couponRef.current,ticket:data.ticket}
          setCurCoupon(data.ticket)
        }
        const ret = await handleCalcPrice(data)
        setPriceMap({
          totalPrice: ret.content.afterDiscountsPrice*1,
          ticketPrice: ret.content.afterDiscountsPrice*1,
          platformVoucherDiscount:ret.content.platformVoucherDiscount
        })
      })
    }
    fetchData()
  },[])
  async function handleCalcPrice(values){  ///  锁定优惠券计算价格
    let ticketCoupon = values?.ticket || couponRef.current.ticket
    const data = {
      orderId: router.params.orderId,
      couponIds: []
    }
    if(ticketCoupon?.length){
      ticketCoupon.map(res=>{
        data.couponIds.push(res.id)
      })
    }
    Taro.showLoading({title:'加载中...'})
    return await Taro.$post('/act/orders/pricing',data,'1')
  }
  useDidShow(()=>{
    // _getWatchList()
  })

  const handleToPay = debounce(async ()=>{
    Taro.showLoading({title:'加载中...'})
    const data = {
      "openId": await Taro.getOpenId(),
      "orderId": info.id,
      "discountAmount":info.discountAmount,
      "isBirdDiscount":info.isBirdDiscount
    }
    if(curCoupon.length){
      const arr = []
      curCoupon.map(res=>{
        arr.push({
          id:res.id,
          name:res.voucherName
        })
      })
      Object.assign(data,{voucherIds:arr,platformVoucherDiscount:priceMap.platformVoucherDiscount})
    }
    if(goodsList.length && goodsList.filter(res=>res.num>0).length){
      let productItemRequestList = []
      goodsList.filter(res=>res.num>0).map(res=>{
        productItemRequestList.push({
          productReleaseId: res.id,
          productVariantReleaseId:res.productVariantReleaseId,
          num:res.num,
          price:res.price
        })
      })
      Object.assign(data,{productItemRequestList})
    }
    Taro.$post('/act/orders/commit',{...data},'1').then(res=>{
      if(res.code === '1'){
        if(res.content.result == '0' || res.content.isZeroOrder){
          Taro.redirectTo({
            url:`/orderSubPack/pay-status/index?id=${res.content.groupOrderId}`
          })
          return;
        }
        Taro.redirectTo({
          url:`/pages/fineEngine/payment?id=${res.content.groupOrderId}`
        })
      }else{
        Taro.$toast(res.message)
      }
    })
  },3000)

  function RoundNum(num, decimal = 2) {
    return Math.round(num * 10 ** decimal) / 10 ** decimal;
  }

  ///          network
  const _getWatchList = async ()=>{
    const res = await Taro.$get('/act/user-certification')
    if(res.code == '1'){
      setwatchList(res.content || [])
      if(res.content.length){
        setcurCheckbox(res.content[0])
      }
    }
  }
  return (
  info.activityId?
  <View className="order-confirm">
    <View className="confirm-header">
      <Image className="header-img" src={Taro.getMedia(info.media)} mode="aspectFill"></Image>
      <View className="header-info">
        <View className="dot2 h2">{info.activityName}</View>
        <View className='p'>{info.location.name} </View>
        <View className='p'>{info.dateStr}</View>
        {info.hallName?<View className='p'>{info.hallName} {info.seats} </View>:null}
        
      </View>
      <View className="confirm-service" onClick={()=>{setPopupService(true)}}>
        <View className='p'><Image className="img" src={require('@/static/check.svg')}></Image>限时退票</View>
        <View className='p'><Image className="img" src={require('@/static/check.svg')}></Image>电子票入场</View>
        <View className="service-span">服务须知 <Text className='at-icon at-icon-chevron-right' style="color:#26282A;font-size:15px"></Text></View>
      </View>
    </View>
    <AtActionSheet isOpened={PopupService} onClose={()=>{setPopupService(false)}}>
      <View className="popup-service">
        <View className="service-header">
          <View className='h2'>服务须知</View>
          <Image onClick={()=>{setPopupService(false)}} src={require('@/static/close.png')} className="header-close"></Image>
        </View>
        <View className="service-list">
          <View className="list-item">
            <Image src={require('@/static/check.svg')} className="item-img"></Image>
            <View className='p'>限时退票</View>
            该活动支持退票，退票需要收取手续费，具体规则如下：
            <View className="item-table">
              <View className="table-header table-main"><Text>申请退票时间段</Text><Text>退票手续费</Text></View>
              <View className="table-body table-main">
                {info.refundRule?.map((res,idx)=>{
                  return <View key={res.timeSlot} className={`body-item ${info.refundRule.findIndex(ret=>ret.selected)>idx?'gary':''}`}><Text>{res.timeSlot}{res.selected?<Text className='item-cur'>当前阶段</Text>:null}</Text><Text>{res.refundServiceCharge}</Text></View>
                })}
              </View>
            </View>
          </View>
          <View className="list-item">
            <Image src={require('@/static/check.svg')} className="item-img"></Image>
            <View className='p'>电子票进场</View>
            在“我的-我的订单”查看订单详情，通过二维码检票进场。
          </View>
        </View>
      </View>
    </AtActionSheet>
    
    <View className="confirm-coupon">
      <View className='h5'>本单可享优惠</View>
      <View className="coupon-main">
        <View className="box-list">
          <View className="box-flex p">优惠活动</View>
          {info.isBirdDiscount?<>
            <View className='tag'>早鸟票特惠</View>
            -¥{info.discountAmount}
          </>:<Text className="span">无可用</Text>}
          <Text className='at-icon at-icon-chevron-right' style="margin-left: 10rpx;font-size:12px"></Text>
        </View>
        <View className="box-list">
          <View className="box-flex p">优惠券</View>
          <View className="span" style={curCoupon.length?{color: '#ff0d49'}:null} onClick={()=>{
            let url = `/mainPages/select-coupon/index?id=${info.activityId}&price=${info.totalPayment}&seatNum=${info.quantity}`
            if(curCoupon.length){
              let result = [];
              for (let i = 0; i < curCoupon.length; i++) {
                result.push(curCoupon[i].id)
              }
              url = url+`&curCoupon=${result.join(',')}`
            }
            Taro.navigateTo({
              url
            })
          }}>{curCoupon.length?curCoupon.length>1?'多券叠加':curCoupon[0]?.voucherName:'选择优惠券'}</View>
          <Text className='at-icon at-icon-chevron-right' style="margin-left: 10rpx;font-size:12px"></Text>
        </View>
      </View>
    </View>
    {/* {info.realName?
    <View className="confirm-watcher">
      <View className="box-flex">
        <h5>实名观演人 <View style="color:#FF0D49">仅需选择1位，入场需携带对应证件。</View></h5>
        <View className="watcher-button" onClick={()=>{handleWatchAdd()}}>新增</View>
      </View>
      <View className="watcher-list">
        <View className="list-item" v-for="(item,index) in watchList" key="item.id">
          <View className="item-title">
            <h2>{item.realName}</h2>
            <p className="p">身份证 {item.idCardNoDesc}</p>
          </View>
          <Image style="width:32rpx;height:32rpx;" src={curCheckbox.id == item.id?require('@/static/block-on.png'):require('@/static/block.png')} mode="widthFix" onClick={()=>{setcurCheckbox(item)}}></Image>
        </View>
      </View>
    </View>:null} */}
    {goodsList.length?
    <View className="confirm-goods">
      <View className='h5'>卖品小食</View>
      {goodsList.map((item,index)=>{
        return <View className="goods-item" key={item.id}>
          <Image src={item.url} className="item-logo"></Image>
          <View className="item-info">
            <View className="dot2 h2">{item.title}</View>
            <View className="dot h3">{item.subTitle}</View>
            <View className="info-price">
              <View className="p">¥{item.price}</View>
              <InputNumber value={item.num} onCut={()=>{
                item.num > 0? item.num-- : item.num = null
                const arr = [...goodsList]
                setgoodsList(arr)
                setgoodsPrice(arr.filter(res=>res.num>0).reduce((preV,curV)=>{
                  return preV+=curV.num*curV.price
                },0))
                setgoodsNum(arr.filter(res=>res.num>0).reduce((preV,curV)=>{
                  return preV+=curV.num
                },0))
              }} onAdd={()=>{
                item.num >= 0? item.num++ : item.num = 1
                if(item.num == item.productCount) return;
                const arr = [...goodsList]
                setgoodsList(arr)
                setgoodsPrice(arr.filter(res=>res.num>0).reduce((preV,curV)=>{
                  return preV+=curV.num*curV.price
                },0))
                setgoodsNum(arr.filter(res=>res.num>0).reduce((preV,curV)=>{
                  return preV+=curV.num
                },0))
              }} />
            </View>
          </View>
        </View>
      })}
      {goodsNum?<View className="goods-info">
        <Text className="span">共{goodsNum}份</Text>
        原价<Text className="strong">¥{RoundNum(goodsPrice)}</Text>
      </View>:null}
    </View>:null}
    <View className="confirm-coupon">
      <View className='h5'>价格明细</View>
      <View className="coupon-main">
        <View className="box-list">
          <View className="box-flex p">演出票合计 <Text>{info.quantity}张</Text></View>
          <View>¥{priceMap.ticketPrice} {info.isBirdDiscount?<Text className='tag' style={{color:'#96989A',borderColor:'#E6E8EA',margin:0}}>已优惠¥{info.discountAmount}</Text>:null}</View>
        </View>
        {goodsNum>0?<View className="box-list">
          <View className="box-flex p">小食合计 <Text>{goodsNum}件</Text></View>
          <Text>¥{RoundNum(goodsPrice)}</Text>
        </View>:null}
        <View className="box-list">
          <View className="box-flex p">电影卡支付</View>
          <Text className='span'>无可用</Text>
        </View>
      </View>
    </View>
    <View className="notice">本项目支持有条件退款，涉及收取退票手续费，具体规则请以本页面“服务须知-条件退票”中展示的规则为准。</View>
    
    <View className="confirm-button">
      {/* <View className="button-textarea">由于票品为有价证券，非普通商品，其背后承载的文化服务具有时效性、稀缺性等特征，一旦订购成功，不支持退换。</View> */}
      <View className="box-flex">
        <View className="button-info">
          <View className='h5'>合计 <Text style="color: #FF0D49; font-size: 20rpx;margin-left: 10rpx;">￥</Text> <Text style="color:#FF0D49; font-size: 36rpx; font-weight: 700;">{RoundNum(priceMap.totalPrice*1 + goodsPrice*1)}</Text></View>
          <CountDownTimer time={time} autoStart={true} onFinish={()=>{
            Taro.navigateBack().catch(()=>{
              Taro.reLaunch({
                url:'/pages/index/index'
              })
            })
          }}></CountDownTimer>
        </View>
        <Button onClick={()=>{handleToPay()}}>立即付款</Button>
      </View>
    </View>
  </View>:null
  )
}
